/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package entidade.controller.JPA;

import entidade.controller.JPA.exceptions.IllegalOrphanException;
import entidade.controller.JPA.exceptions.NonexistentEntityException;
import entidade.controller.JPA.exceptions.RollbackFailureException;
import entidade.persistencia.Vinculo;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidade.persistencia.TipoUsuario;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.UserTransaction;

/**
 *
 * @author victorinox
 */
public class VinculoJpaController {
    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "globalimage2PU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Vinculo vinculo) throws RollbackFailureException, Exception {
        if (vinculo.getTipoUsuarioCollection() == null) {
            vinculo.setTipoUsuarioCollection(new ArrayList<TipoUsuario>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<TipoUsuario> attachedTipoUsuarioCollection = new ArrayList<TipoUsuario>();
            for (TipoUsuario tipoUsuarioCollectionTipoUsuarioToAttach : vinculo.getTipoUsuarioCollection()) {
                tipoUsuarioCollectionTipoUsuarioToAttach = em.getReference(tipoUsuarioCollectionTipoUsuarioToAttach.getClass(), tipoUsuarioCollectionTipoUsuarioToAttach.getTipoUsuarioId());
                attachedTipoUsuarioCollection.add(tipoUsuarioCollectionTipoUsuarioToAttach);
            }
            vinculo.setTipoUsuarioCollection(attachedTipoUsuarioCollection);
            em.persist(vinculo);
            for (TipoUsuario tipoUsuarioCollectionTipoUsuario : vinculo.getTipoUsuarioCollection()) {
                Vinculo oldVinculoIdOfTipoUsuarioCollectionTipoUsuario = tipoUsuarioCollectionTipoUsuario.getVinculoId();
                tipoUsuarioCollectionTipoUsuario.setVinculoId(vinculo);
                tipoUsuarioCollectionTipoUsuario = em.merge(tipoUsuarioCollectionTipoUsuario);
                if (oldVinculoIdOfTipoUsuarioCollectionTipoUsuario != null) {
                    oldVinculoIdOfTipoUsuarioCollectionTipoUsuario.getTipoUsuarioCollection().remove(tipoUsuarioCollectionTipoUsuario);
                    oldVinculoIdOfTipoUsuarioCollectionTipoUsuario = em.merge(oldVinculoIdOfTipoUsuarioCollectionTipoUsuario);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Vinculo vinculo) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Vinculo persistentVinculo = em.find(Vinculo.class, vinculo.getVinculoId());
            List<TipoUsuario> tipoUsuarioCollectionOld = persistentVinculo.getTipoUsuarioCollection();
            List<TipoUsuario> tipoUsuarioCollectionNew = vinculo.getTipoUsuarioCollection();
            List<String> illegalOrphanMessages = null;
            for (TipoUsuario tipoUsuarioCollectionOldTipoUsuario : tipoUsuarioCollectionOld) {
                if (!tipoUsuarioCollectionNew.contains(tipoUsuarioCollectionOldTipoUsuario)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain TipoUsuario " + tipoUsuarioCollectionOldTipoUsuario + " since its vinculoId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<TipoUsuario> attachedTipoUsuarioCollectionNew = new ArrayList<TipoUsuario>();
            for (TipoUsuario tipoUsuarioCollectionNewTipoUsuarioToAttach : tipoUsuarioCollectionNew) {
                tipoUsuarioCollectionNewTipoUsuarioToAttach = em.getReference(tipoUsuarioCollectionNewTipoUsuarioToAttach.getClass(), tipoUsuarioCollectionNewTipoUsuarioToAttach.getTipoUsuarioId());
                attachedTipoUsuarioCollectionNew.add(tipoUsuarioCollectionNewTipoUsuarioToAttach);
            }
            tipoUsuarioCollectionNew = attachedTipoUsuarioCollectionNew;
            vinculo.setTipoUsuarioCollection(tipoUsuarioCollectionNew);
            vinculo = em.merge(vinculo);
            for (TipoUsuario tipoUsuarioCollectionNewTipoUsuario : tipoUsuarioCollectionNew) {
                if (!tipoUsuarioCollectionOld.contains(tipoUsuarioCollectionNewTipoUsuario)) {
                    Vinculo oldVinculoIdOfTipoUsuarioCollectionNewTipoUsuario = tipoUsuarioCollectionNewTipoUsuario.getVinculoId();
                    tipoUsuarioCollectionNewTipoUsuario.setVinculoId(vinculo);
                    tipoUsuarioCollectionNewTipoUsuario = em.merge(tipoUsuarioCollectionNewTipoUsuario);
                    if (oldVinculoIdOfTipoUsuarioCollectionNewTipoUsuario != null && !oldVinculoIdOfTipoUsuarioCollectionNewTipoUsuario.equals(vinculo)) {
                        oldVinculoIdOfTipoUsuarioCollectionNewTipoUsuario.getTipoUsuarioCollection().remove(tipoUsuarioCollectionNewTipoUsuario);
                        oldVinculoIdOfTipoUsuarioCollectionNewTipoUsuario = em.merge(oldVinculoIdOfTipoUsuarioCollectionNewTipoUsuario);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = vinculo.getVinculoId();
                if (findVinculo(id) == null) {
                    throw new NonexistentEntityException("The vinculo with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Vinculo vinculo;
            try {
                vinculo = em.getReference(Vinculo.class, id);
                vinculo.getVinculoId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The vinculo with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<TipoUsuario> tipoUsuarioCollectionOrphanCheck = vinculo.getTipoUsuarioCollection();
            for (TipoUsuario tipoUsuarioCollectionOrphanCheckTipoUsuario : tipoUsuarioCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Vinculo (" + vinculo + ") cannot be destroyed since the TipoUsuario " + tipoUsuarioCollectionOrphanCheckTipoUsuario + " in its tipoUsuarioCollection field has a non-nullable vinculoId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(vinculo);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Vinculo> findVinculoEntities() {
        return findVinculoEntities(true, -1, -1);
    }

    public List<Vinculo> findVinculoEntities(int maxResults, int firstResult) {
        return findVinculoEntities(false, maxResults, firstResult);
    }

    private List<Vinculo> findVinculoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Vinculo as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Vinculo findVinculo(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Vinculo.class, id);
        } finally {
            em.close();
        }
    }

    public int getVinculoCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Vinculo as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
